import { observer } from "mobx-react-lite";
import { useEffect, useState } from "react";
import Taro, { navigateBack, showToast } from "@tarojs/taro";
import { View, Text } from "@tarojs/components";
import {
  Form,
  Input,
  Radio,
  TextArea,
  Uploader,
  Button,
} from "@nutui/nutui-react-taro";
import { Checklist, Location } from "@nutui/icons-react-taro";
import TagComp from "@/components/Tag";
import "./index.less";
import Navbar from "@/components/Navbar";
import { HouseEntity } from "@/entities/HouseEntity";
import HouseBusiness from "@/business/HouseBusiness";
import ImageConstant from "@/constant/ImageConstant";
import CodeConstant from "@/constant/CodeConstant";
import houseStore from "@/stores/HouseStore";
import authStore from "@/stores/AuthStore";
import systemStore from "@/stores/SystemStore";
import { HouseConstant } from "@/constant/HouseConstant";
import useHouse from "@/hooks/useHouse";

function EnterHouse() {
  const { HouseToStatusMap, FieldToUnit } = HouseConstant;
  const { currentHouse } = houseStore;
  const { againGetLandlordHouseList } = useHouse();
  let status;
  // 是否是编辑
  const [isEditor, setIsEditor] = useState(false);
  // 房屋id
  const [houseId, setHouseId] = useState<number>();
  // 地址id
  const [addressId, setAddressId] = useState<number>();
  // 默认值
  const [defaultHouseName, setDefaultHouseName] = useState<string>();
  const [defaultPrice, setDefaultPrice] = useState<number>();
  const [defaultWaterFee, setDefaultWaterFee] = useState<number>();
  const [defaultElectricityFee, setDefaultElectricityFee] = useState<number>();
  const [defaultInternetFee, setDefaultInternetFee] = useState<number>();
  const [defaultFuelFee, setDefaultFuelFee] = useState<number>();
  const [defaultArea, setDefaultArea] = useState<number>();
  const [defaultFloor, setDefaultFloor] = useState<number>();
  const [defaultDepositNumber, setDefaultDepositNumber] = useState(1);
  const [defaultPriceNumber, setDefaultPriceNumber] = useState(1);
  const [defaultToward, setDefaultToward] = useState(3);
  const [defaultToilet, setDefaultToilet] = useState(2);
  const [defaultBalcony, setDefaultBalcony] = useState(2);
  const [defaultKitchen, setDefaultKitchen] = useState(2);
  const [defaultNote, setDefaultNote] = useState<string>();
  const [defaultHouseImg, setDefaultHouseImg] = useState<Array<any>>([]);

  // 地址
  const [address, setAddress] = useState("");
  // 详细地址
  const [addressDetail, setAddressDetail] = useState("");
  // 经纬度
  const [longitude, setLongitude] = useState(0);
  const [latitude, setLatitude] = useState(0);
  // 房屋图片列表
  const [houseImgList, setHouseImgList] = useState<Array<string>>([]);

  /**
   * 校验成功触发的函数
   */
  const handleFinish = async (values: Partial<HouseEntity.IBaseHouse> = {}) => {
    const {
      name = defaultHouseName,
      price = defaultPrice,
      waterFee = defaultWaterFee,
      electricityFee = defaultElectricityFee,
      internetFee = defaultInternetFee,
      fuelFee = defaultFuelFee,
      depositNumber = defaultDepositNumber,
      priceNumber = defaultPriceNumber,
      area = defaultArea,
      floor = defaultFloor,
      toward = defaultToward,
      toilet = defaultToilet,
      balcony = defaultBalcony,
      kitchen = defaultKitchen,
      note,
    } = values;
    if (!name)
      return showToast({
        title: "名称不能为空！",
        icon: "error",
      });
    if (!price)
      return showToast({
        title: "租金不能为空！",
        icon: "error",
      });
    if (!waterFee || !electricityFee || !internetFee || !fuelFee)
      return showToast({
        title: "其他费用不能为空！",
        icon: "error",
      });
    if (!depositNumber || !priceNumber)
      return showToast({
        title: "付款方式不能为空！",
        icon: "error",
      });
    if (!area || !floor)
      return showToast({
        title: "实体信息不能为空！",
        icon: "error",
      });
    if (houseImgList.length === 0)
      return showToast({
        title: "至少上传一张图片！",
        icon: "error",
      });

    const houseReq: HouseEntity.IAddHouseReq = {
      name,
      area,
      price,
      depositNumber,
      priceNumber,
      floor,
      toward,
      toilet,
      kitchen,
      balcony,
      waterFee,
      electricityFee,
      internetFee,
      fuelFee,
      addressName: address,
      addressDetail,
      latitude,
      longitude,
      houseImg: JSON.stringify(houseImgList),
      note,
      status,
    };

    new Promise(async (resolve) => {
      if (!isEditor) {
        // 添加房屋
        await HouseBusiness.addHouse(houseReq);
        resolve("");
      } else {
        // 更新房屋
        await HouseBusiness.updateHouse({
          ...houseReq,
          houseId: houseId!,
          addressId: addressId!,
        });
        resolve("");
      }
    }).then(() => {
      againGetLandlordHouseList();
      navigateBack();
    });
  };
  /**
   * 点击编辑时的房屋数据
   */
  const updateData = (house: HouseEntity.IResultHouse) => {
    setIsEditor(true);
    setHouseId(house.houseId);
    setAddressId(house.addressId);
    setDefaultHouseName(house.name);
    setDefaultPrice(house.price);
    setDefaultWaterFee(house.waterFee);
    setDefaultElectricityFee(house.electricityFee);
    setDefaultInternetFee(house.internetFee);
    setDefaultFuelFee(house.fuelFee);
    setDefaultDepositNumber(house.depositNumber);
    setDefaultPriceNumber(house.priceNumber);
    setDefaultArea(house.area);
    setDefaultFloor(house.floor);
    setDefaultToward(house.toward);
    setDefaultToilet(house.toilet);
    setDefaultKitchen(house.kitchen);
    setDefaultBalcony(house.balcony);
    setAddress(house.addressName);
    setAddressDetail(
      house.provinceName + house.cityName + house.areaName + house.addressInfo
    );
    setLatitude(house.latitude);
    setLongitude(house.longitude);
    setDefaultNote(house.note || "");
    setHouseImgList(JSON.parse(house.houseImg || "[]"));
  };

  useEffect(() => {
    currentHouse && updateData(currentHouse);
    return () => {
      houseStore.clearEditorCurrentHouse();
    };
  }, []);

  useEffect(() => {
    setDefaultHouseImg(
      houseImgList.map((url: string) => {
        return {
          status: "success",
          url: `${ImageConstant.SERVER_ROOT}${url}`,
          type: "image",
        };
      })
    );
  }, [houseImgList]);

  /**
   *  处理地址位置选择
   */
  const handleSelectAddress = () => {
    Taro.chooseLocation({
      success(res) {
        const { address, name, latitude, longitude } = res;
        setAddress(name);
        setAddressDetail(address);
        setLongitude(longitude);
        setLatitude(latitude);
      },
      fail() {
        Taro.showToast({
          title: "位置获取失败！",
          icon: "error",
        });
      },
    });
  };

  /**
   * 房屋图片上传成功回调
   */
  const houseImgUploadSuccess = ({ responseText }) => {
    const res: any = JSON.parse(responseText.data);
    if (res.code !== CodeConstant.SUCCESS) {
      showToast({ title: "图片上传失败！", icon: "error" });
      return;
    }
    showToast({ title: "图片上传成功！", icon: "success" });
    setHouseImgList((houseImgList) => [...houseImgList, res.data]);
  };

  /**
   * 房屋图片上传失败回调
   */
  const houseImgUploadFail = () => {
    showToast({ title: "图片上传失败！", icon: "error" });
  };

  /**
   * 删除图片时触发的回调
   */
  const houseImgDelete = async ({ url }: any) => {
    const strArr = url.split("/");
    const imgName = "/" + strArr[strArr.length - 1];
    setHouseImgList((houseImgList) =>
      houseImgList.filter((i) => i !== imgName)
    );
  };

  /**
   * 自定义上传组件
   * @constructor
   */
  const CustomUploader = () => {
    return (
      <Uploader
        url={ImageConstant.UPLOAD_IMG_VIDEO}
        maxCount={6}
        multiple={true}
        defaultValue={defaultHouseImg}
        headers={{ authorization: authStore.token }}
        onSuccess={houseImgUploadSuccess}
        onFailure={houseImgUploadFail}
        onDelete={houseImgDelete}
      />
    );
  };

  return (
    <Navbar
      title={isEditor ? "编辑房屋" : "添加房屋"}
      mode="back"
      bgColor="var(--mini-first)"
    >
      <View
        style={{ height: systemStore.haveNavbarNotTabbarHeight }}
        className="enter-house-container"
      >
        <Form
          labelPosition="right"
          onFinish={handleFinish}
          footer={
            <View className="add-house-btn-group">
              <Button
                formType="submit"
                type="info"
                className="release-btn"
                onTap={() => {
                  status = HouseToStatusMap.notLeaseReleased;
                }}
              >
                发布
              </Button>
              <Button
                formType="submit"
                type="primary"
                className="submit-btn"
                onClick={() => {
                  status = HouseToStatusMap.notLeaseNotReleased;
                }}
              >
                提交
              </Button>
            </View>
          }
          className="form-wrap"
        >
          <View className="form-item">
            <Text className="input-text">名称：</Text>
            <View className="input-wrap">
              <Form.Item name="name" initialValue={defaultHouseName}>
                <Input placeholder="请输入" />
              </Form.Item>
            </View>
          </View>

          <View className="form-item">
            <Text className="input-text">租金：</Text>
            <View className="input-wrap">
              <TagComp content="￥" bgColor="var(--mini-first)" />
              <Form.Item name="price" initialValue={defaultPrice}>
                <Input placeholder="请输入" type="number" />
              </Form.Item>
            </View>
          </View>
          <View className="form-item">
            <Text className="input-text">图片：</Text>
            <Form.Item name="houseImg">
              <CustomUploader />
            </Form.Item>
          </View>

          {/* 其他费用 */}
          <View className="little-title">其他费用：</View>
          <View className="flex enterHouse-little-wrap">
            <View className="form-item">
              <View className="input-wrap">
                <TagComp content="水" bgColor="var(--mini-first)" />
                <Form.Item
                  name="waterFee"
                  className="flex-1"
                  initialValue={defaultWaterFee}
                >
                  <Input type="number" placeholder=" " align="right" />
                </Form.Item>
                <Text className="input-unit-text">{FieldToUnit.waterFee}</Text>
              </View>
            </View>

            <View className="form-item">
              <View className="input-wrap">
                <TagComp content="电" bgColor="var(--mini-third)" />
                <Form.Item
                  name="electricityFee"
                  className="flex-1"
                  initialValue={defaultElectricityFee}
                >
                  <Input type="number" placeholder=" " align="right" />
                </Form.Item>
                <Text className="input-unit-text">
                  {FieldToUnit.electricityFee}
                </Text>
              </View>
            </View>
          </View>
          <View className="flex enterHouse-little-wrap">
            <View className="form-item">
              <View className="input-wrap">
                <TagComp content="网" bgColor="var(--mini-fourth)" />
                <Form.Item
                  name="internetFee"
                  className="flex-1"
                  initialValue={defaultInternetFee}
                >
                  <Input type="number" placeholder=" " align="right" />
                </Form.Item>
                <Text className="input-unit-text">
                  {FieldToUnit.internetFee}
                </Text>
              </View>
            </View>

            <View className="form-item">
              <View className="input-wrap">
                <TagComp content="气" bgColor="var(--mini-fifth)" />
                <Form.Item
                  name="fuelFee"
                  className="flex-1"
                  initialValue={defaultFuelFee}
                >
                  <Input type="number" placeholder=" " align="right" />
                </Form.Item>
                <Text className="input-unit-text">{FieldToUnit.fuelFee}</Text>
              </View>
            </View>
          </View>
          {/* 付款方式 */}
          <View className="little-title">付款方式：</View>
          <View className="flex enterHouse-little-wrap">
            <View className="form-item">
              <View className="input-wrap">
                <Text className="text-light-grey">押：</Text>
                <Form.Item
                  name="depositNumber"
                  className="flex-1"
                  initialValue={defaultDepositNumber}
                >
                  <Input type="number" placeholder=" " align="right" />
                </Form.Item>
                <TagComp
                  content="月"
                  bgColor="var(--mini-first)"
                  style={{ margin: "0 0 0 4px" }}
                />
              </View>
            </View>
            <View className="form-item">
              <View className="input-wrap">
                <Text className="text-light-grey">付：</Text>
                <Form.Item
                  name="priceNumber"
                  className="flex-1"
                  initialValue={defaultPriceNumber}
                >
                  <Input type="number" placeholder=" " align="right" />
                </Form.Item>
                <TagComp
                  content="月"
                  bgColor="var(--mini-third)"
                  style={{ margin: "0 0 0 4px" }}
                />
              </View>
            </View>
          </View>
          {/* 实体信息 */}
          <View className="little-title">实体信息：</View>
          <View className="flex enterHouse-little-wrap">
            <View className=" form-item">
              <View className="input-wrap">
                <Text className="text-light-grey whitespace-nowrap">
                  面积：
                </Text>
                <Form.Item
                  name="area"
                  className="flex-1"
                  initialValue={defaultArea}
                >
                  <Input type="number" placeholder=" " align="right" />
                </Form.Item>
                <TagComp
                  content="方"
                  bgColor="var(--mini-first)"
                  style={{ margin: "0 0 0 4px" }}
                />
              </View>
            </View>
            <View className="form-item">
              <View className="input-wrap">
                <Text className="text-light-grey whitespace-nowrap">
                  楼层：
                </Text>
                <Form.Item
                  name="floor"
                  className="flex-1"
                  initialValue={defaultFloor}
                >
                  <Input type="number" placeholder=" " align="right" />
                </Form.Item>
                <TagComp
                  content="层"
                  bgColor="var(--mini-third)"
                  style={{ margin: "0 0 0 4px" }}
                />
              </View>
            </View>
          </View>
          <View className="form-item">
            <Text className="input-text">朝向：</Text>
            <Form.Item name="toward" initialValue={defaultToward}>
              <Radio.Group direction="horizontal">
                <Radio value={1} activeIcon={<Checklist />}>
                  东
                </Radio>
                <Radio value={2} activeIcon={<Checklist />}>
                  西
                </Radio>
                <Radio value={3} activeIcon={<Checklist />}>
                  南
                </Radio>
                <Radio value={4} activeIcon={<Checklist />}>
                  北
                </Radio>
              </Radio.Group>
            </Form.Item>
          </View>
          <View className="form-item">
            <Text className="input-text">卫生间：</Text>
            <Form.Item name="toilet" initialValue={defaultToilet}>
              <Radio.Group direction="horizontal">
                <Radio value={1} activeIcon={<Checklist />}>
                  没有
                </Radio>
                <Radio value={2} activeIcon={<Checklist />}>
                  独立
                </Radio>
                <Radio value={3} activeIcon={<Checklist />}>
                  公用
                </Radio>
              </Radio.Group>
            </Form.Item>
          </View>
          <View className="form-item">
            <Text className="input-text">厨房：</Text>
            <Form.Item name="kitchen" initialValue={defaultKitchen}>
              <Radio.Group direction="horizontal">
                <Radio value={1} activeIcon={<Checklist />}>
                  没有
                </Radio>
                <Radio value={2} activeIcon={<Checklist />}>
                  独立
                </Radio>
                <Radio value={3} activeIcon={<Checklist />}>
                  公用
                </Radio>
              </Radio.Group>
            </Form.Item>
          </View>
          <View className="form-item">
            <Text className="input-text">阳台：</Text>
            <Form.Item name="balcony" initialValue={defaultBalcony}>
              <Radio.Group direction="horizontal">
                <Radio value={1} activeIcon={<Checklist />}>
                  有
                </Radio>
                <Radio value={2} activeIcon={<Checklist />}>
                  无
                </Radio>
              </Radio.Group>
            </Form.Item>
          </View>
          <View className="form-item address-wrap">
            <Text className="input-text">地址：</Text>
            <Input
              placeholder=" "
              value={address}
              onFocus={handleSelectAddress}
            />
            <Location
              color="var(--font-fourth)"
              onClick={handleSelectAddress}
              style={{ padding: "0 16px" }}
            />
          </View>
          <View className="form-item address-wrap">
            <Text className="input-text">详细地址：</Text>
            <Input
              name="addressDetail"
              placeholder=" "
              value={addressDetail}
              onChange={(val) => setAddressDetail(val)}
            />
          </View>
          <View className="form-item">
            <Text className="input-text">备注：</Text>
            <Form.Item
              name="note"
              initialValue={defaultNote}
              className="text-area-wrap"
            >
              <TextArea showCount maxLength={200} className="text-area" />
            </Form.Item>
          </View>
        </Form>
      </View>
    </Navbar>
  );
}

export default observer(EnterHouse);
